import { Alert, Checkbox, Form, Button, Input, Result, Tooltip } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import { router } from 'umi';
import { ConnectProps, ConnectState } from '@/models/connect';
import { post } from '@/utils/request';
import * as api from '@/constants/api';
import { getBaseHost, toast } from '@/utils/utils';
import Cookies from 'js-cookie';
import { LOGIN_COOKIE_KEY, LOGIN_ROLE_KEY } from '@/constants/index';
import styles from './index.less';

const Login: React.FC<ConnectProps> = props => {
  // @ts-ignore
  const { target } = props.location.query;

  const isValid = !!target;
  const [isLogining, setIsLogining] = useState(false);

  const login = (values: any) => {
    setIsLogining(true);
    post(api.LOGIN, values)
      .then(res => {
        // 写入cookie，开始跳转页面
        const resData = res;
        const baseHost = getBaseHost();
        Cookies.set(LOGIN_COOKIE_KEY, resData.token, { domain: baseHost, expires: 365 });
        Cookies.set(LOGIN_ROLE_KEY, resData.role, { domain: baseHost, expires: 365 });

        const targetUrl = decodeURIComponent(target);
        if (/^http/.test(targetUrl)) {
          window.location.href = targetUrl;
        } else {
          router.push(targetUrl);
        }
        setIsLogining(false);
      })
      .catch(err => {
        setIsLogining(false);
      });
  };

  return isValid ? (
    <div className={styles.main}>
      <Form onFinish={login}>
        <Form.Item name="account" rules={[{ required: true, message: '请输入账号!' }]}>
          <Input prefix={<UserOutlined />} placeholder="请输入账号" />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
          <Input.Password prefix={<LockOutlined />} placeholder="请输入密码"></Input.Password>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={isLogining}>
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  ) : (
    <Result status="404" title="" subTitle="你的访问姿势不正确，请检查入参" />
  );
};

export default Login;
